import os
from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse
from django.http import HttpResponseRedirect
from dns import models
from . import handler
from datetime import datetime


def check_login(fn):
    def wrapper(request, *args, **kwargs):
        if request.session.get('IS_LOGIN', False):
            return fn(request, *args, *kwargs)
        else:
            next = request.get_full_path()
            red = HttpResponseRedirect('/login/?next=' + next)
            return red
    return wrapper


def LoginHandler(request):
    if request.method == 'POST':
        payload = request.POST
        username = payload['username']
        password = payload['password']
        # 获取复选框value值，以列表的形式，没有选中value值为空
        remember = payload.getlist('remember')
        # 登录后对next的url进行操作,为空跳转至产品的首页
        next_url = request.GET.get('next', "/dashboard/")
        # 密码验证
        user = models.User.objects.filter(username=username)

        if user is not None and user[0].password == password:
            # 记录用户登录状态,存储到session当中
            # login(request, user)
            request.session["IS_LOGIN"] = True
            request.session["username"] = username
            response = redirect(next_url)
            if len(remember) == 1:
                response.set_cookie('name', username, max_age=7*24*3600)
            else:
                response.delete_cookie('name')
            return response
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    if 'name' in request.COOKIES:
        username = request.COOKIES.get('name', 0)
    else:
        username = ''
    return render(request, 'login.html', {'username': username})


@check_login
def IndexHandler(request):

    data = {
            "domain": len(models.Domain.objects.all()),
            "record": len(models.Record.objects.all()),
            "user":  len(models.User.objects.all()),
            "uptime": handler.get_uptime(),
            "ip": handler.get_ip(),
            "net": handler.net_stat(),
            "mem": handler.get_mem(),
            "load": handler.get_load(),
            "os": handler.get_os_version(),
            "hdd": handler.get_hdd(),
            "dnsmasq": handler.get_dnsmasq(),
            "hostname": handler.get_hostname(),
            "cpu": handler.get_cpu()
    }
    return render(request, "index.html", {"data": data})


@check_login
def DnsDomainHandler(request):
    if request.method == "POST":
        domain = request.POST.get("domain")
        file = request.POST.get("file")
        comment = request.POST.get("comment")
        fun = request.POST.get("fun", "add")
        if fun == "add":
            domain_list = models.Domain.objects.filter(domain=domain)
            if len(domain_list) > 1:
                msg = "2"
                return HttpResponse(msg)
            f = open("/etc/dnsmasq.d/" + file, 'w')
            f.write("# " + domain + "\n")
            f.close()
            file_md5 = handler.get_md5("/etc/dnsmasq.d/" + file)
            domain = models.Domain(domain=domain, comment=comment, file=file)
            domain.save()
            msg = "1"
            return HttpResponse(msg)
        elif fun == "edit":
            id = request.POST.get("id")
            models.Domain.objects.filter(id=id).update(domain=domain, comment=comment, file=file, update_time=datetime.now())
            msg = "1"
            return HttpResponse(msg)

    domains = models.Domain.objects.all()
    return render(request, "domain.html", {"domains": domains})


@check_login
def DnsRecordHandler(request):
    did = request.GET.get("did", 0)
    if request.method == "POST":
        did = request.POST.get("did")
        record = request.POST.get("record")
        type = request.POST.get("type")
        value = request.POST.get("value")
        priority = request.POST.get("priority", 1)
        comment = request.POST.get("comment")
        fun = request.POST.get("fun", "add")
        print(type, value, priority)
        if type == "MX":
            priority = int(priority)
        if fun == "add":
            Record = models.Record(did=did, record=record, type=type, value=value, comment=comment, priority=priority)
            Record.save()
            msg = "1"
            return HttpResponse(msg)
        elif fun == "edit":
            id = request.POST.get("id")
            models.Record.objects.filter(id=id).update(record=record, type=type, value=value, priority=priority, comment=comment, update_time=datetime.now())
            msg = "1"
            return HttpResponse(msg)
    cur_domain = models.Domain.objects.filter(id=did).first()
    domains = models.Domain.objects.all()
    records = models.Record.objects.filter(did=did)
    return render(request, "record.html", {"did": int(did), "records": records, "domains": domains, "cur_domain": cur_domain})


@check_login
def DnsServerHandler(request):
    if request.method == "POST":
        address = request.POST.get("address")
        comment = request.POST.get("comment")
        fun = request.POST.get("fun", "add")
        if fun == "add":
            domain_list = models.DnsServer.objects.filter(address=address)
            if len(domain_list) > 1:
                msg = "2"
                return HttpResponse(msg)

            dns = models.DnsServer(address=address, comment=comment)
            dns.save()
            msg = "1"
            return HttpResponse(msg)
        elif fun == "edit":
            id = request.POST.get("id")
            models.DnsServer.objects.filter(id=id).update(address=address, comment=comment, update_time=datetime.now())
            msg = "1"
            return HttpResponse(msg)

    dns = models.DnsServer.objects.all()
    return render(request, "dns_server.html", {"dns": dns})


@check_login
def UsersHandler(request):
    if request.method == "POST":
        username = request.POST.get("username",None)
        name = request.POST.get("name",None)
        email = request.POST.get("email",None)
        mobile = request.POST.get("mobile",None)
        password = request.POST.get("password",None)
        comment = request.POST.get("comment",None)
        id = request.POST.get("id",None)
        fun = request.POST.get("fun")
        if fun == "add":
            models.User.objects.create(username=username, name=name, email=email, mobile=mobile, password= password, comment=comment)
            msg = "1"
            return HttpResponse(msg)
        elif fun == "edit":
            models.User.objects.filter(id=id).update(name=name, email=email, mobile=mobile, comment=comment, mdate=datetime.now())
            msg = "1"
            return HttpResponse(msg)
        elif fun == "pass":
            models.User.objects.filter(id=id).update(password=password)
            msg = "1"
            return HttpResponse(msg)
    users = models.User.objects.all()
    return render(request, "users.html", {"users": users})


def LoginLogsHandler(request):
    logs = models.LoginLog.objects.all()
    return render(request, "users_logs.html", {"logs":logs})

@check_login
def PublicAPIHandler(request):
    module = request.GET.get("module")
    fun = request.GET.get("fun")
    value = request.GET.get("value", None)
    id = request.GET.get("id", None)
    redirect_id = request.GET.get("did", None)
    if module == "record":
        if fun == "ch_status":
            models.Record.objects.filter(id=id).update(status=value)
            return redirect("/dns/record/?did=" + redirect_id)
        elif fun == "del":
            models.Record.objects.filter(id=id).delete()
            return redirect("/dns/record/?did=" + redirect_id)
    elif module == "domain":
        if fun == "ch_status":
            models.Domain.objects.filter(id=id).update(status=value)
            return redirect("/dns/domain/")
        elif fun == "del":
            domain = models.Domain.objects.filter(id=id).first()
            os.remove("/etc/dnsmasq.d/" + domain.file)
            models.Record.objects.filter(did=id).delete()
            domain.delete()
            return redirect("/dns/domain/")
    elif module == "dns":
        if fun == "ch_status":
            models.DnsServer.objects.filter(id=id).update(status=value)
            return redirect("/dns/server/")
        elif fun == "del":
            models.DnsServer.objects.filter(id=id).delete()
            return redirect("/dns/server/")
        elif fun == "rsync":
            dns = models.DnsServer.objects.filter(status="yes")
            file_content = ''
            for data in dns:
                file_content += "nameserver  " + data.address + "\n"
            f = open("/etc/resolv.dnsmasq.conf", "w")
            f.write(file_content)
            f.close()
            msg = "0"
            return HttpResponse(msg)
    elif module == "dnsmasq":  # 同步解析
        if fun == "rsync":  # 从数据库更新配置文件并重新加载服务
            domain = models.Domain.objects.filter(status="yes", id=id)
            if len(domain) == 0:
                msg = "2"
                return HttpResponse(msg)
            else:
                domain = domain[0]
                records = models.Record.objects.filter(did=id)
                file_content = ''
                for record in records:
                    if record.type == "A":
                        file_content += "address=/" + record.record + "." + domain.domain + "/" + record.value + "\n"
                    elif record.type == "MX":
                        file_content += "mx-host=" + domain.domain + "," + record.value + "," + str(record.priority) + "\n"
                    elif record.type == "TXT":
                        file_content += "txt-record="
                        if record.record != "@":
                            file_content += record.record + "."
                        file_content += domain.domain + ',"' + record.value + '"\n'
                    elif record.type == "CNAME":
                        file_content += "cname=" + record.record + "." + domain.domain + "," + record.value + "\n"
                f = open("/etc/dnsmasq.d/" + domain.file, "w")
                f.write(file_content)
                f.close()
                sv_rt = os.system("systemctl restart dnsmasq")
                if sv_rt == 0:
                    msg = "0"  # 成功
                else:
                    msg = "1"  # 服务重启失败
                return HttpResponse(msg)

        elif fun in ("restart", "start", "stop"):
            sv_rt = os.system("systemctl " + fun + " dnsmasq")
            msg = "0" if sv_rt == 0 else "1"
            return HttpResponse(msg)
    elif module == "users":
        if fun == "ch_status":
            models.User.objects.filter(id=id).update(status=value)
            return redirect("/users")
        elif fun == "del":
            models.User.objects.filter(id=id).delete()
            return redirect("/users")
    elif module == "login_logs":
        msg = "1"
        if fun == "clear":
            username = request.session["username"]
            models.LoginLog.objects.filter(username=username).delete()
            msg = "0"
        return HttpResponse(msg)


def LogoutHandler(request):
    request.session["IS_LOGIN"] = False
    return redirect("/login/")

